/*
 * =====================================================================================
 *
 *       Filename:  csv.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  09/09/18 22:35:26
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andy
 *        Company:  
 *
 * =====================================================================================
 */

#include "csv.h"

void get_two_dimension(char* line, double** data, const char *filename)
{
    FILE* stream = fopen(filename, "r");
    int i = 0;
    while (fgets(line, 1024, stream))//逐行读取
    {
        int j = 0;
        char *tok;
        char* tmp = strdup(line);
        for (tok = strtok(line, ","); tok && *tok; j++, tok = strtok(NULL, ",\n")){
            data[i][j] = atof(tok);//转换成浮点数 
        }//字符串拆分操作 
        i++;
        free(tmp);
    }
    fclose(stream);//文件打开后要进行关闭操作
}

void print_two_dimension(double** data, int row, int col)
{
    int i, j;
    for(i=1; i<row; i++){
        for(j=0; j<col; j++){
            printf("%f\t", data[i][j]);
        }
        printf("\n");
    }//打印的时候不打印第一行，第一行全是字符
}

int get_row(const char *filename)
{
    char line[1024 * 8];
    int i = 0;
    FILE* stream = fopen(filename, "r");
    while(fgets(line, 1024, stream)){
        i++;
    }
    fclose(stream);
    return i;
}

int get_col(const char *filename)
{
    char line[1024 * 8];
    int i = 0;
    FILE* stream = fopen(filename, "r");
    fgets(line, 1024, stream);
    char* token = strtok(line, ",");
    while(token){
        token = strtok(NULL, ",");
        i++;
    }
    fclose(stream);
    return i;
}


